package com.example.stgv;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Checkable;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class AddStudent extends Activity {

	private DBHelper db;
	Button btnThem, btnXoa, btnSua, btnThoat;
	LopHocsData lop = new LopHocsData();
	HocSinhData hs = new HocSinhData();
	Spinner sp_namhoc, sp_lophoc;
	ListView lvDanhSach;
	TextView txthoten, txtngaysinh, txtdiachi, txtmahs;
	RadioButton rbtnam, rbtnu;
	String slmalop;
	ArrayList<HocSinhData> arrhocsinhObj;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_add_student);

		txtmahs = (TextView) findViewById(R.id.student_txtMaHS);
		txthoten = (TextView) findViewById(R.id.student_txtTenHS);
		txtngaysinh = (TextView) findViewById(R.id.student_txtNgaySinhHS);
		txtdiachi = (TextView) findViewById(R.id.student_txtdiachi);
		rbtnam = (RadioButton) findViewById(R.id.student_rdb_boy);
		rbtnu = (RadioButton) findViewById(R.id.student_rdb_girl);

		loadDataToLop();

		btnThoat = (Button) findViewById(R.id.student_btnCancel);
		btnThoat.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();

			}
		});
		btnThem = (Button) findViewById(R.id.addstudent_btnAdd);

		btnThem.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				if (checkData()) {
					if (insertHocSinh()) {
						setData();
					}
				}
			}
		});
		btnXoa = (Button) findViewById(R.id.addstudent_btnXoa);

		btnXoa.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {

				if (txtmahs.getText().toString().isEmpty()) {
					Log.d("Thong bao", "Chua chon hoc sinh.");
					Toast.makeText(AddStudent.this,
							"Vui lòng chọn HS cần xóa.", Toast.LENGTH_SHORT)
							.show();
				} else {
					if (deleteHocSinh(txtmahs.getText().toString())) {
						setData();
					}
				}
			}
		});

		btnSua = (Button) findViewById(R.id.addstudent_btnSua);
		btnSua.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				if (txtmahs.getText().toString().isEmpty()) {
					Log.d("Thong bao", "Chua chon hoc sinh.");
					Toast.makeText(AddStudent.this,
							"Vui lòng chọn HS cần sửa.", Toast.LENGTH_SHORT)
							.show();
				} else {
					if (checkData()) {
						updateHocSinh(txtmahs.getText().toString());
						setData();
					}
				}
			}
		});

		lvDanhSach = (ListView) this.findViewById(R.id.student_lvDanhSach);
		lvDanhSach.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				txtmahs.setText(arrhocsinhObj.get(arg2).getKEY_MAHS()
						.toString());
				txthoten.setText(arrhocsinhObj.get(arg2).getKEY_TENHS()
						.toString());
				txtngaysinh.setText(arrhocsinhObj.get(arg2).getKEY_NGAYSINH()
						.toString());
				txtdiachi.setText(arrhocsinhObj.get(arg2).getKEY_DIACHI()
						.toString());

				if (arrhocsinhObj.get(arg2).getKEY_TENHS().toString()
						.equals("1")) {
					rbtnam.setChecked(true);
				} else {
					rbtnam.setChecked(true);
				}
				Log.d("Thong bao", "Ma HS "
						+ arrhocsinhObj.get(arg2).getKEY_MAHS().toString());
				Log.d("Thong bao", "arg3 "
						+ arrhocsinhObj.get(arg2).getKEY_TENHS().toString());
			}
		});

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.my_menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			Intent openSetting = new Intent(this, SettingsActivity.class);
			startActivity(openSetting);
		} else if (id == R.id.act_diemdanh) {
			Intent openAttStudent = new Intent(this, AttStudent.class);
			startActivity(openAttStudent);
		} else if (id == R.id.act_diem) {
			Intent openInputScore = new Intent(this, InputScore.class);
			startActivity(openInputScore);
		} else if (id == R.id.action_newHS) {
			Intent openStudent = new Intent(this, AddStudent.class);
			startActivity(openStudent);
		} else if (id == R.id.action_newLop) {
			Intent openClass = new Intent(this, AddClass.class);
			startActivity(openClass);
		} else {
		}
		return super.onOptionsItemSelected(item);
	}

	protected boolean updateHocSinh(String str) {

		try {
			int nParam = 5;
			String[] fields = new String[nParam];
			String[] values = new String[nParam];
			String[] wherearg = new String[1];
			String whereClause = "mahs=?";

			fields[0] = hs.getKEY_TENHS();
			fields[1] = hs.getKEY_NGAYSINH();
			fields[2] = hs.getKEY_GIOITINH();
			fields[3] = hs.getKEY_DIACHI();
			fields[4] = lop.getKEY_MALOP();

			values[0] = txthoten.getText().toString();
			values[1] = txtngaysinh.getText().toString().trim();
			values[2] = rbtnam.isChecked() ? "1" : "0";
			values[3] = txtdiachi.getText().toString();
			values[4] = slmalop;

			wherearg[0] = str;

			db.UpdateData(hs.getDATABASE_TABLE_HOCSINH(), nParam, fields,
					values, whereClause, wherearg);
			Toast.makeText(this, "Đã sửa học sinh này. " + str,
					Toast.LENGTH_SHORT).show();
			db.close();
			return true;
		} catch (Exception e) {
			Log.d("Insert", "Không thể sửa ");
			Toast.makeText(this, "Lỗi sai dữ liệu.", Toast.LENGTH_SHORT).show();
			return false;
		}
	}

	protected boolean deleteHocSinh(String i) {

		String[] whereArgs = new String[1];
		whereArgs[0] = i;
		Cursor cur = db.runAllDateRQ(
				"select mahs from diemdanh where mahs = ?", whereArgs);
		Cursor cur1 = db.runAllDateRQ("select mahs from diem where mahs = ?",
				whereArgs);
		Log.d("Thong bao", "da truy van.");
		if ((cur != null && cur.getCount() > 0) || cur1 != null
				&& cur1.getCount() > 0) {
			Log.d("Thong bao", "da nhap diem hoac diem danh");
			Toast.makeText(
					this,
					" Không xóa được \n Học sinh đã có điểm hoặc đã điểm danh. ",
					Toast.LENGTH_SHORT).show();
			return false;
		} else {
			long deletelop = db.deleteData("hocsinh", "mahs = ?", whereArgs);
			Log.d("Thong bao", "Da xoa hoc sinh" + whereArgs[0]);
			Toast.makeText(this, "Đã xóa học sinh này. " + i,
					Toast.LENGTH_SHORT).show();
		}
		cur1.close();
		cur.close();
		loadDataHocSinh(slmalop);
		return true;
	}

	protected void loadDataToLop() {
		sp_lophoc = (Spinner) this.findViewById(R.id.student_spLop);
		ArrayList<String> arrLopHoc = new ArrayList<String>();
		final ArrayList<String> arrMalop = new ArrayList<String>();
		db = new DBHelper(AddStudent.this);
		Cursor cur = db
				.runAllDateRQ("select distinct malop, tenlop from lop order by tenlop");
		if (cur.moveToFirst()) {
			do {
				arrLopHoc.add(cur.getString(1));
				arrMalop.add(cur.getString(0));
			} while (cur.moveToNext());
		}
		cur.close();
		db.close();
		ArrayAdapter<String> l_arrayAdapter = new ArrayAdapter<String>(
				this.getApplicationContext(),
				android.R.layout.simple_spinner_item, arrLopHoc);
		l_arrayAdapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		sp_lophoc.setAdapter(l_arrayAdapter);
		sp_lophoc.setSelection(0);
		sp_lophoc
				.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

					@Override
					public void onItemSelected(AdapterView<?> arg0, View arg1,
							int arg2, long arg3) {

						slmalop = arrMalop.get((int) arg3).toString();
						Log.d("Thong bao", "Da chon Lop " + slmalop);
						loadDataHocSinh(slmalop);
					}

					@Override
					public void onNothingSelected(AdapterView<?> arg0) {

					}
				});
		setData();
	}

	protected void loadDataHocSinh(String sllophoc) {

		String[] values = new String[1];
		values[0] = sllophoc;
		arrhocsinhObj = new ArrayList<HocSinhData>();

		db = new DBHelper(this);
		Cursor cur = db
				.runAllDateRQ(
						"select mahs,tenhs,gioitinh,ngaysinh,diachi from hocsinh where malop=?",
						values);
		if (cur.moveToFirst()) {
			do {
				arrhocsinhObj.add(new HocSinhData(cur.getString(0), cur
						.getString(1), cur.getString(2), cur.getString(3), cur
						.getString(4)));
			} while (cur.moveToNext());
		}
		cur.close();
		db.close();
		HocSinhAdaptor adapter = new HocSinhAdaptor(this, arrhocsinhObj);
		lvDanhSach.setAdapter(adapter);

	}

	private Boolean insertHocSinh() {
		try {
			int nParam = 5;
			String[] fields = new String[nParam];
			String[] values = new String[nParam];
			String[] wherearg = new String[2];

			fields[0] = hs.getKEY_TENHS();
			fields[1] = hs.getKEY_NGAYSINH();
			fields[2] = hs.getKEY_GIOITINH();
			fields[3] = hs.getKEY_DIACHI();
			fields[4] = lop.getKEY_MALOP();

			values[0] = txthoten.getText().toString();
			values[1] = txtngaysinh.getText().toString().trim();
			values[2] = rbtnam.isChecked() ? "1" : "0";
			values[3] = txtdiachi.getText().toString();
			values[4] = slmalop;

			wherearg[0] = values[0];
			wherearg[1] = values[1];

			db = new DBHelper(AddStudent.this);
			long a = db.insertData(hs.getDATABASE_TABLE_HOCSINH(), nParam,
					fields, values);
			db.close();
			if (a >= 0) {
				Toast.makeText(this, "Đã thêm vào một học sinh " + a,
						Toast.LENGTH_SHORT).show();
				loadDataHocSinh(slmalop);
				return true;
			} else {
				Toast.makeText(this, "Không thêm được" + values[0],
						Toast.LENGTH_SHORT).show();
				return false;

			}

		} catch (Exception e) {
			Log.d("Insert", "Không thể insert. ");
			Toast.makeText(this, "Lỗi sai dữ liệu.", Toast.LENGTH_SHORT).show();
			return false;
		}
	}

	public Boolean checkData() {
		if (txthoten.getText().toString().isEmpty()
				|| txtngaysinh.getText().toString().isEmpty()) {
			Toast.makeText(this, "Thiếu dữ liệu.", Toast.LENGTH_SHORT).show();
			return false;
		}
		return true;
	}

	public void setData() {
		txtmahs.setText("");
		txthoten.setText("");
		txthoten.requestFocus();
		txtdiachi.setText("");
		txtngaysinh.setText("");
	}
}
